/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: BookListFragmentPresenter.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.kline.presenter;

import android.text.TextUtils;
import android.util.Log;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.math.BigDecimal;
import java.sql.SQLOutput;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import io.bhex.app.base.AppUI;
import io.bhex.sdk.quote.bean.DepthDataBean;
import io.bhex.app.utils.NumberUtils;
import io.bhex.app.utils.copy.DeepCopy;
import io.bhex.baselib.mvp.BaseCoreActivity;
import io.bhex.baselib.mvp.BaseFragmentPresenter;


public class BookListFragmentPresenter extends BaseFragmentPresenter<BookListFragmentPresenter.EntrustOrderUI> {

    private static final String TAG = "BookListFragmentPresenter";
    private DepthDataBean currentDepthData;

    public interface EntrustOrderUI extends AppUI{

        void showDepthView(DepthDataBean data);

        void getDepthDataFailed(String msg);

        float getDigitNum2();

        int getDigitNum();

        String getDigitStr();
    }

    @Override
    public void onUIReady(BaseCoreActivity activity, BookListFragmentPresenter.EntrustOrderUI ui) {
        super.onUIReady(activity, ui);
    }

    @Override
    public void onResume() {

    }

    @Override
    public void onPause() {
        super.onPause();
    }

    /**
     * 深度数据
     * @param depthDataBean
     */
    DepthDataBean udata;
    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void onMessageEvent(DepthDataBean depthDataBean) {
        //System.out.println("depthDataBean=="+Thread.currentThread().getName());
        if (depthDataBean == null)
            return;
        DepthDataBean data = (DepthDataBean) DeepCopy.copy(depthDataBean);
        //由小到大
        List<List<String>> a = data.getA();
        //由大到小
        List<List<String>> b = data.getB();
//        if (a == null||a.isEmpty()||b==null||b.isEmpty()) {
//            //数据有问题不在展示
//            DebugLog.w(TAG,"深度数据返回有问题,不再更新界面");
//            return;
//        }

        if (data.getA() != null) {
            a = data.getA();
        }else{
            a = new ArrayList<>();
        }
        if (data.getB() != null) {
            b = data.getB();
        }else{
            b = new ArrayList<>();
        }

        currentDepthData = data;
        //排序
        data = sortData(data, depthDataBean.f);
        udata = data;

        getUI().showDepthView(udata);
    }


    public void mergerData(){
        if (currentDepthData != null) {
            DepthDataBean data = sortData(currentDepthData, false);
            getUI().showDepthView(data);
        }
    }


    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }


    Map<String, String> sourceMapA = new TreeMap<>();
    Map<String, String> sourceMapB = new TreeMap<>();

    /**
     * 数据排序
     * @param depthDataBean
     * @return
     */
    private DepthDataBean sortData(DepthDataBean depthDataBean, boolean f) {
        try {
            //暂时忽略变化，每次以最新数据处理
            if(f == true) {
                sourceMapA.clear();
                sourceMapB.clear();
            }
            //增删数据 value挂单量为零
            List<List<String>> a = depthDataBean.getA();
            for (List<String> result : a) {
                float value = TextUtils.isEmpty(result.get(1)) ? 0 : Float.valueOf(result.get(1));
                if (value > 0) {
                    sourceMapA.put(result.get(0), result.get(1));
                } else {
                    sourceMapA.remove(result.get(0));
                }
            }

            List<List<String>> b = depthDataBean.getB();
            for (List<String> result : b) {
                float value = TextUtils.isEmpty(result.get(1)) ? 0 : Float.valueOf(result.get(1));
                if (value > 0) {
                    sourceMapB.put(result.get(0), result.get(1));
                } else {
                    sourceMapB.remove(result.get(0));
                }

            }

            Map<String, String> zipMapA = zipData(sourceMapA, true);
            Map<String, String> zipMapB = zipData(sourceMapB, false);

            zipMapA = sortMapByKey(zipMapA);
            zipMapB = sortMapByKey(zipMapB);

            //组装数据
            List<List<String>> A = new ArrayList<>();
            for (String key : zipMapA.keySet()) {
                ArrayList<String> item = new ArrayList<>();
                item.add(key);
                item.add(zipMapA.get(key));
                A.add(item);
            }
            depthDataBean.setA(A);

            List<List<String>> B = new ArrayList<>();
            for (String key : zipMapB.keySet()) {
                ArrayList<String> item = new ArrayList<>();
                item.add(key);
                item.add(zipMapB.get(key));
                B.add(item);
            }
            depthDataBean.setB(B);
        }catch (Exception e){
            e.printStackTrace();
        }
        return depthDataBean;
    }

    /**
     * 压缩数据(合并价格，累加挂单量)
     * @param map
     * @return
     */
    private Map<String,String> zipData(Map<String, String> map, boolean up) {
        int digitNum = getUI().getDigitNum();
        float digitNum2 = getUI().getDigitNum2();
        String digitStr = getUI().getDigitStr();

        Map<String, String> newMap = new TreeMap<>();
        for (String key : map.keySet()) {
//            DebugLog.e("DIGIT","原始："+key);
//            int digitCount = NumberUtils.calNumerCount(getActivity(), digitStr);

            String newKey = "";
            if(up)
                newKey = NumberUtils.roundUpString(key,digitNum);
            else
                newKey = NumberUtils.roundDownString(key,digitNum);
//            DebugLog.e("DIGIT","处理："+newKey);
            float value = Float.valueOf(map.get(key));
            String s = newMap.get(newKey);
            s=TextUtils.isEmpty(s)?"0":s;
            float newValue = Float.valueOf(s)+value;//累计量
            newMap.put(newKey,newValue+"");
        }
        return newMap;
    }


    /**
     * 使用 Map按key进行排序
     * @param map
     * @return
     */
    public static Map<String, String> sortMapByKey(Map<String, String> map) {
        if (map == null || map.isEmpty()) {
            return new TreeMap<String,String>();
        }

        Map<String, String> sortMap = new TreeMap<String, String>(
                new DepthViewPresenter.MapKeyComparator());

        sortMap.putAll(map);

        return sortMap;
    }


    //比较器类
    static class MapKeyComparator implements Comparator<String> {

        @Override
        public int compare(String str1, String str2) {

            return new BigDecimal(str1).compareTo(new BigDecimal(str2));
        }
    }
}
